package com.yuanda.erp9.syn.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Pattern;

public class EasyExcelUtils {


    //纯数字
    private static Pattern patternNum = Pattern.compile("[^0-9]");

    //纯数字
    private static String priceString = "^[-\\+]?[.\\d]*$";


    /**
     * @Description: 解析excel，默认不实现(new consumer来实现)
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/179:45
     */
    public static <T> void readExcel(String path, Class<T> T, Consumer<T> consumer) {
        EasyExcel.read(path, T, new SyncReadListener() {
            @Override
            public void invoke(Object object, AnalysisContext context) {
                consumer.accept((T) object);
            }
        }).doReadAll();
    }

    /**
     * @Description: 解析excel，默认不实现(new consumer来实现)
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/179:45
     */
    public static <T> void readExcelAsStream(InputStream inputStream, Class<T> T, Consumer<T> consumer) {
        EasyExcel.read(inputStream, T, new SyncReadListener() {
            @Override
            public void invoke(Object object, AnalysisContext context) {
                consumer.accept((T) object);
            }
        }).doReadAll();
    }

    /**
     * @Description: 读取指定sheet 同步读取
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/115:36
     */
    public static <T> void readExcelBySheet(String path, Class<T> T, Consumer<T> consumer, String sheetName) {
        EasyExcel.read(path, T, new SyncReadListener() {
            @Override
            public void invoke(Object object, AnalysisContext context) {
                consumer.accept((T) object);
            }
        }).sheet(sheetName).headRowNumber(1).doReadSync();
    }


    /**
     * 处理批次号
     *
     * @param batchNo
     * @return
     */
    public static String processingBatchNumber(String batchNo) {
        String result = "";
        if (StringUtils.isEmpty(batchNo)) {
            return result;
        }
        if (batchNo.length() != 6) {
            return result;
        }
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        if (Integer.parseInt(batchNo.substring(batchNo.lastIndexOf(".") + 1, 4)) > year) {
            return result;
        }
        return batchNo.substring(2, 6);
    }


    /**
     * @Description: 处理coreStaff批次号
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/2/2317:05
     */
    public static String parseBatchNo(String batchNo) {
        if (StringUtils.isEmpty(batchNo) || "N/A".equals(batchNo)) {
            return "";
        }
        String newBatchNo = batchNo.substring(2);
        return !batchNo.contains("+") ? newBatchNo + "+" : newBatchNo;
    }


    /***
     *  获取incodes
     * @param sign sign = hisp+“_”+型号+“_”+自增id
     * @param crmNum  固定写死,用户id,必填
     * @param name 型号 如果sign为空为必填
     * @param batch  批次 如果sign为空为必填
     * @param postting  封装 如果sign为空为必填
     * @param packing 包装 如果sign为空为必填
     * @param depot 库房 如果sign为空为必填
     * @param suppliersId 供应商id,必填
     *
     * @return
     */
    public static String getIncodes(String sign, String crmNum, String name, String batch, String postting, String packing, String depot, Integer suppliersId) {
        if (StringUtils.isEmpty(crmNum)) {
            return "";
        }
        if (suppliersId == null) {
            return "";
        }
        String text = "";
        if (StringUtils.isEmpty(sign)) {
            text = name + "-" + getCodes(name, batch, sign, postting, packing, crmNum, depot);
        }
        if (sign.length() > 16) {
            text = encrypt32(sign);
        } else {
            text = sign;
        }
        return text + "-" + suppliersId;
    }


    /**
     * @Description: 这俩个参数不为空使用此方法
     * @Params: @sign sign = hisp+“_”+型号+“_”+自增id   @crmNum 固定写死,用户id,必填
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/11/3016:25
     */
    public static String getIncodes(String sign, String crmNum, Integer suppliersId) {
        return getIncodes(sign, crmNum, null, null, null, null, null, suppliersId);
    }


    /**
     * 处理crmNum
     *
     * @param crmNum 用户id
     * @return
     */
    public static String patternCrmNum(String crmNum) {
        String crmNumPattern = patternNum.matcher(crmNum).replaceAll("");
        //去除前边所有的0
        return crmNumPattern.replaceAll("^(0+)", "");
    }

    /**
     * 处理codes
     *
     * @param name     型号
     * @param batch    批次
     * @param sign     签名
     * @param postting 封装
     * @param packing  包装
     * @param crmNum   用户id
     * @param depot    库房
     * @return
     */
    private static String getCodes(String name, String batch, String sign, String postting, String packing, String crmNum, String depot) {
        String text = name + "-" + batch + "-" + sign + "-" + batch + "-" + postting + "-" + packing + "-" + crmNum + "-" + depot;
        String textMd5 = encrypt32(text);
        return textMd5 + "-" + patternCrmNum(crmNum);
    }


    /**
     * 16位MD5加密算法
     *
     * @param encryptStr
     * @return
     */
    private static String encrypt32(String encryptStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = md5.digest(encryptStr.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff;
                if (val < 16)
                    hexValue.append("0");
                hexValue.append(Integer.toHexString(val));
            }
            encryptStr = hexValue.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return encryptStr.toUpperCase().substring(8, 24);
    }

    /**
     * @param param
     * @return
     */
    public static boolean isPrice(String param) {
        if (StringUtils.isEmpty(param)) {
            return false;
        }
        return param.matches(priceString);
    }


    /**
     * @Description: 生成map费率
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/1215:07
     */
    public static Map<String, String> getRateMap(String VATRate, String TariffRate, String ExciseTaxRate, String CIQprice, String AddedTariffRate, String CustomsExchangeRate) {
        //{"VATRate":0,"TariffRate":0,"ExciseTaxRate":0,"CIQprice":0,"AddedTariffRate":0,"CustomsExchangeRate":7.0363}
        Map<String, String> rateMap = new HashMap<>();
        rateMap.put("VATRate", VATRate);
        rateMap.put("TariffRate", TariffRate);
        rateMap.put("ExciseTaxRate", ExciseTaxRate);
        rateMap.put("CIQprice", CIQprice);
        rateMap.put("AddedTariffRate", AddedTariffRate);
        rateMap.put("CustomsExchangeRate", CustomsExchangeRate);
        return rateMap;
    }


    /**
     * 是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (!com.innovation.ic.b1b.framework.util.StringUtils.validateParameter(str)) {
            return false;
        }
        return patternNum.matcher(str).matches();
    }

}